package net.simpleos.backend.permission;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.IQueryEntitySet;
import net.simpleframework.ado.db.SQLValue;
import net.simpleframework.organization.IJob;
import net.simpleframework.organization.IUser;
import net.simpleframework.organization.OrgUtils;
import net.simpleframework.organization.impl.JobMember;
import net.simpleframework.util.StringUtils;
import net.simpleos.SimpleosUtil;

/**
 * 
 * @author 李岩飞 
 * @email eliyanfei@126.com
 * @date 2014年11月29日 下午10:06:56 
 *
 */
public class PlatformUtis {
	public static Lock lock = new ReentrantLock();
	public static boolean hasPermission = false;//是否绑定了权限菜单
	public static Map<String, PermissionSession> DEFAULT_MENUS = new ConcurrentHashMap<String, PermissionSession>();

	public static void initUserMenu(final String sessionId, final IUser user, final boolean login) {
		try {
			lock.lock();
			if (login) {
				DEFAULT_MENUS.remove(sessionId);
			}
			//菜单已经绑定
			PermissionSession permissionSession = DEFAULT_MENUS.get(sessionId);
			if (permissionSession == null) {
				permissionSession = new PermissionSession();
			}
			if (permissionSession.menuMap.size() > 0) {
				return;
			}
			// 用户没有指定角色时返回空
			final Object[] jobIdArray = PlatformUtis.getJobIds(user);
			if (jobIdArray == null || jobIdArray.length <= 0) {
				return;
			}
			// 获取用户所属角色的所有菜单
			IQueryEntitySet<Map<String, Object>> qs = SimpleosUtil.getTableEntityManager(SimpleosUtil.applicationModule, PermissionBean.class).query(
					new SQLValue(
							"SELECT DISTINCT C.`NAME`,C.URL FROM simpleos_menu_catalog c,simpleos_platform_permission p where c.`name`=p.menu_name and p.job_id in ("
									+ StringUtils.join(jobIdArray, ",") + ")"));
			Map<String, Object> data = null;
			while ((data = qs.next()) != null) {
				permissionSession.menuMap.put(String.valueOf(data.get("NAME")), String.valueOf(data.get("URL")));
			}
			if (user != null) {
				DEFAULT_MENUS.put(sessionId, permissionSession);
			}
		} finally {
			lock.unlock();
		}
	}

	/**
	 * 获取当前登录用户的所有角色信息
	 * 
	 * @param user
	 *            登录用户
	 * @return
	 */
	public static List<JobMember> getJobMembersByUser(final IUser user) {
		final List<JobMember> jobMemberList = new ArrayList<JobMember>();
		final IQueryEntitySet<JobMember> jobMembers = OrgUtils.getTableEntityManager(JobMember.class).query(
				new ExpressionValue(" memberid = ? ", new Object[] { user.getId().getValue() }), JobMember.class);
		JobMember jobMember = null;
		while ((jobMember = jobMembers.next()) != null) {
			jobMemberList.add(jobMember);
		}
		return jobMemberList;
	}

	public static Object[] getJobIds(final IUser user) {
		final List<Object> jobIds = new ArrayList<Object>();
		if (user != null && !user.getId().equals2(0)) {
			final List<JobMember> jobMembers = getJobMembersByUser(user);
			jobIds.add(OrgUtils.jm().getJobByName(IJob.sj_account_normal).getId());
			jobIds.add(OrgUtils.jm().getJobByName(IJob.sj_anonymous).getId());
			for (final JobMember jobMember : jobMembers) {
				jobIds.add(jobMember.getJobId().getValue());
			}
		} else {
			jobIds.add(OrgUtils.jm().getJobByName(IJob.sj_anonymous).getId());
		}
		return jobIds.toArray(new Object[jobIds.size()]);
	}
}
